package com.zego.zegowawaji_server;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.widget.Toast;

import com.bugtags.library.Bugtags;
import com.tencent.bugly.crashreport.CrashReport;
import com.zego.base.utils.AppLogger;
import com.zego.base.utils.DeviceIdUtil;
import com.zego.base.utils.PrefUtil;
import com.zego.base.utils.TimeUtil;
import com.zego.manager.ModuleMgr;
import com.zego.zegoliveroom.ZegoLiveRoom;
import com.zego.zegoliveroom.constants.ZegoAvConfig;
import com.zego.zegoliveroom.constants.ZegoConstants;

/**
 * 初始化SDK
 */

public class ZegoApplication extends Application {

    static final private long APP_ID = 3846947654L;
    static final private byte[] APP_SIGN_KEY = new byte[]{
            (byte) 0x84, (byte) 0x93, (byte) 0xaf, (byte) 0xc1, (byte) 0x5b, (byte) 0xf7, (byte) 0xda, (byte) 0xbf,
            (byte) 0xf9, (byte) 0x55, (byte) 0x0e, (byte) 0x1c, (byte) 0xa6, (byte) 0x5c, (byte) 0x53, (byte) 0x97,
            (byte) 0xb3, (byte) 0xe4, (byte) 0x9b, (byte) 0xfa, (byte) 0x24, (byte) 0xba, (byte) 0x30, (byte) 0xbe,
            (byte) 0x0a, (byte) 0x08, (byte) 0xa6, (byte) 0xdf, (byte) 0x9f, (byte) 0xcf, (byte) 0x8c, (byte) 0x08
    };
    static final private String BUGLY_APP_KEY = "61437f8eb3";
    public static String deviceId ;
    public static Context context;
    static private ZegoApplication sInstance;
    private ZegoLiveRoom mZegoLiveRoom;

    static public ZegoApplication getAppContext() {
        return sInstance;
    }

    public static Context getContext() {
        return context;
    }

    public ZegoLiveRoom getZegoLiveRoom() {
        return mZegoLiveRoom;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        sInstance = this;
        context = getApplicationContext();
        deviceId = DeviceIdUtil.generateDeviceId(context);

        AppLogger.getInstance().writeLog("******* Application onCreate *******");

        ModuleMgr.initModule(this);

        initUserInfo(); // first

        initCrashReport();  // second

        setupZegoSDK(); // last

        Bugtags.start("c57d9f34d04f2d7d27d62b25f5f0a79c", this, Bugtags.BTGInvocationEventNone);
    }

    /**
     * 设置用户信息
     */
    private void initUserInfo() {
        String userId = PrefUtil.getInstance().getUserId();
        String userName = PrefUtil.getInstance().getUserName();
        if (TextUtils.isEmpty(userId) || TextUtils.isEmpty(userName)) {
            userId = TimeUtil.getNowTimeStr();
            userName = String.format("WWJS_%s_%s", Build.MODEL.replaceAll(",", "."), userId);

            PrefUtil.getInstance().setUserId(userId);
            PrefUtil.getInstance().setUserName(userName);
        }
    }

    private void initCrashReport() {
        CrashReport.initCrashReport(this, BUGLY_APP_KEY, false);
        CrashReport.setUserId(PrefUtil.getInstance().getUserId());
    }

    private void setupZegoSDK() {
        ZegoLiveRoom.setUser(PrefUtil.getInstance().getUserId(), PrefUtil.getInstance().getUserName());
        ZegoLiveRoom.requireHardwareEncoder(true);
        ZegoLiveRoom.requireHardwareDecoder(true);
        ZegoLiveRoom.setConfig("camera_orientation_mode=0");//设置视频方向
        ZegoLiveRoom.setTestEnv(true);    // 配置测试环境

        mZegoLiveRoom = new ZegoLiveRoom();
        mZegoLiveRoom.setSDKContext(new ZegoLiveRoom.SDKContext() {
            @Override
            public String getSoFullPath() {
                return null;
            }

            @Override
            public String getLogPath() {
                return null;
            }

            @Override
            public Application getAppContext() {
                return sInstance;
            }
        });

        initZegoSDK(mZegoLiveRoom);
    }

    private void initZegoSDK(ZegoLiveRoom liveRoom) {
        boolean success = liveRoom.initSDK(APP_ID, APP_SIGN_KEY);
        if (!success) {
            AppLogger.getInstance().writeLog("Init ZegoLiveRoom SDK failed");
            Toast.makeText(sInstance, "", Toast.LENGTH_LONG).show();
            return;
        }

        int resolutionLevel;
        ZegoAvConfig config;
        int level = PrefUtil.getInstance().getLiveQuality();
        if (level < 0) {
            // 默认设置级别为"标准"
            resolutionLevel = ZegoAvConfig.Level.Generic;

            config = new ZegoAvConfig(resolutionLevel);

            // 保存默认设置
            PrefUtil.getInstance().setLiveQuality(resolutionLevel);
            PrefUtil.getInstance().setLiveQualityResolution(resolutionLevel);
            PrefUtil.getInstance().setLiveQualityFps(15);
            PrefUtil.getInstance().setLiveQualityBitrate(600);
        } else if (level > ZegoAvConfig.Level.SuperHigh) {
            resolutionLevel = PrefUtil.getInstance().getLiveQualityResolution();

            config = new ZegoAvConfig(ZegoAvConfig.Level.High);
            config.setVideoBitrate(PrefUtil.getInstance().getLiveQualityBitrate());
            config.setVideoFPS(PrefUtil.getInstance().getLiveQualityFps());
        } else {
            resolutionLevel = level;
            config = new ZegoAvConfig(level);
        }

        String resolutionText = getResources().getStringArray(R.array.zg_resolutions)[resolutionLevel];
        String[] strWidthHeight = resolutionText.split("x");

        int height = Integer.parseInt(strWidthHeight[0].trim());
        int width = Integer.parseInt(strWidthHeight[1].trim());
        config.setVideoEncodeResolution(width, height);
        config.setVideoCaptureResolution(width, height);

        liveRoom.setAVConfig(config);
        liveRoom.setAVConfig(config, ZegoConstants.PublishChannelIndex.AUX);
    }
}
